<?php
/**
 * @ClassName: Store
 * @Description: TODO
 * @author: gydtrade
 * @Date: 2025-10-16 09:51
 * @Version: V1.0.0
 */

namespace app\api\controller;

use app\common\model;

class Store extends Api
{
    protected $noNeedLogin = ['getStroeClass', 'getNearbyStore'];

    /**
     * 获取店铺分类
     * @return \think\response\Json
     */
    function getStroeClass()
    {
        $where = [];
        $where[] = ['is_show', '=', 1];

        $list = model\StoreCategory::where($where)->order('sort')->select();

        return json(['code' => 1, 'data' => $list]);
    }

    /**
     * 附近门店
     * @return \think\response\Json
     */
    public function getNearbyStore()
    {
        $longitude = input('longitude', '');
        $latitude = input('latitude', '');
        $keyword = input('keyword', '');
        $category_id = input('category_id', 0);
        $type = input('type', 0);////0全部商家，1推荐商家，2附近商家
        $user_type = input('user_type', 1);//用户类型，1联盟商家，2水站商家
        $skip = input('skip', 0);
        $limit = input('limit', 10);

        $where = [];
        $where[] = ['status', '=', 1];//状态：-1已禁用，0待审核，1已通过，2已驳回，3锁定，4申请中
        $where[] = ['user_type', '=', $user_type];

        if ($keyword) {
            $where[] = ['store_name', 'like', '%' . $keyword . '%'];
        }

        if ($category_id) {
            $where[] = ['category_id', '=', $category_id];
        }

        if ($longitude && $latitude) {
            $field = "*, round(st_distance_sphere(point(longitude, latitude), point(" . $longitude . ", " . $latitude . ")) / 1000, 2) as distance";
        } else {
            $field = "*, '' as distance";
        }

        $order = "rating desc";
        // 全部
        if ($type == 0) {
            $order = "rating desc,distance asc";
        }

        // 推荐
        if ($type == 1) {
            $where[] = ['is_recommend', '=', 1];
            $order = "distance asc,rating desc";
        }

        // 最近
        if ($type == 2) {
            $order = "distance asc,rating desc";
        }

        $list = model\Store::where($where)
            ->field($field)
            ->order($order)
            ->limit($skip, $limit)
            ->select();

        $result = [
            'list' => $list,
            'is_more' => count($list) >= $limit
        ];

        return json(['code' => 1, 'msg' => '获取成功', 'data' => $result]);
    }

    /**
     * 切换店铺
     * @return \think\response\Json
     */
    function switchStore()
    {
        $store_id = input('store_id', 0);

        $store = model\Store::get($store_id);

        if (!$store) {
            return json(['code' => 0, 'msg' => '店铺异常']);
        }

        $res = model\Store::where('id', $store_id)->update([
            'last_login_time' => date_now(),
            'update_time' => date_now(),
        ]);

        if (!$res) {
            return json(['code' => 0, 'msg' => '切换店铺失败']);
        }

        return json(['code' => 1, 'msg' => '切换店铺成功']);
    }

}